package mephisto.rest;

import java.util.logging.Level;

import mephisto.Mephisto;
import mephisto.Constants;
import mephisto.rest.resources.BrowserAuthenticationResource;

import org.restlet.Context;
import org.restlet.Guard;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Form;
import org.restlet.data.Request;
import com.noelios.restlet.http.HttpConstants;

public class Authenticator extends Guard {

    public Authenticator(Context context) throws IllegalArgumentException {
        super(context, ChallengeScheme.HTTP_BASIC, Constants.class.getName());
    }

    @Override
    public int authenticate(Request request) {
        if (request.getResourceRef().getPath().endsWith(BrowserAuthenticationResource.URI_PATTERN)) {
            return super.authenticate(request);
        }

        Form headers = (Form) request.getAttributes().get(HttpConstants.ATTRIBUTE_HEADERS);

        Form queryParameters = request.getResourceRef().getQueryAsForm();
        if (queryParameters.getValues("login") == null) {
            if (headers.getValues(HttpConstants.HEADER_AUTHORIZATION) == null) {
                headers.add(HttpConstants.HEADER_AUTHORIZATION, "Basic R3Vlc3Q6");
            }
        }

        return super.authenticate(request);
    }

    @Override
    public boolean checkSecret(Request request, String identifier, char[] secret) {

        mephisto.Context mcontext = (mephisto.Context) getContext().getAttributes().get(Constants.CONTEXT);
        Mephisto mephisto = (Mephisto) getContext().getAttributes().get(Constants.MEPHISTO);

        try {
            if (identifier.equals("guest")) {
                //xwikiContext.setUser("XWiki.XWikiGuest");
                getLogger().log(Level.FINE, String.format("Authenticated a '%s'.", identifier));
                getContext().getAttributes().put(Constants.USER, "guest");

                return true;
            }

            if (mephisto.getAuthenticationService().authenticated(identifier, new String(secret), mcontext)) {
                //String xwikiUser = String.format("XWiki.%s", identifier);
                
                mcontext.put("user",identifier);
                getLogger().log(Level.FINE, String.format("Authenticated as '%s'.", identifier));
                getContext().getAttributes().put(Constants.USER, identifier);

                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        getLogger().log(Level.WARNING, String.format("Cannot authenticate '%s'.", identifier));

        return false;
    }
}
